<%--
 *
 * IBM Confidential
 *
 * OCO Source Materials
 *
 * 5724-M19
 *
 * (C) COPYRIGHT IBM CORP. 2006
 *
 * The source code for this program is not published or otherwise
 * divested of its trade secrets, irrespective of what has been
 * deposited with the U.S. Copyright Office.
 *
--%>

<%--
 *
 * MRO Software Confidential
 *
 * (C) COPYRIGHT MRO Software, Inc. 2001-2006
 *
 * The source code for this program is not published or otherwise
 * divested of its trade secrets, irrespective of what has been
 * deposited with the U.S. Copyright Office.
 *
--%>

<%--
  * @author openmaximo.net
  * @version 0.1 (Maximo v6.2.1)
  * <h3>Table Excel download management</h3>
  * <p>
  * Downloading tables to Excel will be managed by an application which filters 
  * the fields to download to Excel by user group and application.
  * </p>
--%>

<%@ page contentType="application/vnd.ms-excel" import= "psdi.webclient.system.beans.*, psdi.webclient.system.controller.*, psdi.mbo.*, java.util.*, java.io.*,psdi.util.*,net.openmaximo.log.*,net.openmaximo.maximo.app.excelconfig.*" %>

<%
	response.setContentType("application/vnd.ms-excel");
	((HttpServletResponse)response).setHeader("Pragma", "public");
	((HttpServletResponse)response).setHeader("Cache-Control", "max-age=0");
	response.setContentType("application/vnd.ms-excel");
	response.setHeader("Content-Disposition","attachment; filename=download.xls" );
//******************************************************************************
// File: download.jsp : to be included for downloading the table data in "Microsoft
//						Excel" format.
//******************************************************************************
%>
<%
  String tableid = request.getParameter("table");

	SessionContext sessionContext = SessionContext.getSessionContext(request);
	ControlHandler control = RequestHandler.findHandler(sessionContext, tableid);
	DataBean tableBean = Utility.getDataSource(sessionContext, control);
	
	Iterator index = control.getChildren().listIterator();
	ControlHandler tableBodyControl = null;
	while (index.hasNext())
	{
		ControlHandler child = (ControlHandler) index.next();
		String controltype = (String)((ControlProperties) child.getProperties()).getString(sessionContext, "controltype");
		String mxtablepart = (String)((ControlProperties) child.getProperties()).getString(sessionContext, "mxtablepart");
		if(controltype.equals("tablebody") || mxtablepart.equals("tablebody"))
		{
			tableBodyControl = child;
			break;
		}
	}

	boolean def_flds_bool = true;
	boolean can_dw_bool = true;
	
	int childCount = 0;
	ArrayList children = tableBodyControl.getChildren();
	if (children != null) {
		childCount = children.size();
		Iterator jIterator = tableBodyControl.getChildren().listIterator();
		ArrayList dataAttributes = new ArrayList();

		
		String attrName = null;
		String tableMboName = tableBean.getMboName();
	  // Get user information.
		MXSession sesion = tableBean.getMXSession();
		if (sesion != null) {
		  Log4jLogger.debug(ExcelConfig.class," Session exists.");
			String userName = sesion.getUserName();
			String grpNames = new String();
			MboSetRemote grpUsrMboSet = sesion.getMboSet("GROUPUSER");
			grpUsrMboSet.setQbeExactMatch(true);
			if (grpUsrMboSet != null) {
			  Log4jLogger.info(ExcelConfig.class," Group user.");
				grpUsrMboSet.setQbe("userid",userName);
				grpUsrMboSet.reset();
				boolean first = true;
				for(MboRemote grpUsrMbo = grpUsrMboSet.moveFirst(); grpUsrMbo != null; grpUsrMbo = grpUsrMboSet.moveNext()) {
				  if (first) {
				  	grpNames.concat("=").concat(grpUsrMbo.getString("groupname"));
				  } else {
				    grpNames.concat(",=").concat(grpUsrMbo.getString("groupname"));
				  }
				}
			}
			// Get the EXCELCONFIG Mbo.
			Log4jLogger.debug(ExcelConfig.class," EXCELCONFIG.");
			MboSetRemote mboSet = sesion.getMboSet("EXCELCONFIG");
			if (mboSet != null) {
			  Log4jLogger.debug(ExcelConfig.class," Got EXCELCONFIG");
			  mboSet.setQbeExactMatch(true);
				mboSet.setQbe("objectname", tableMboName);
				mboSet.setQbe("groupname", grpNames);
				mboSet.reset();
				// If there is only one record it is managed in a distinct way. 
				// If the only record has a blank name it means the user is not allowed to download to excel.
				if ((mboSet.count() == 1) && (mboSet.getMbo(0).isNull("ATTRIBUTENAME"))) {
				  Log4jLogger.info(ExcelConfig.class," User cannot download to excel.");
			    can_dw_bool = false;
				}
				if (can_dw_bool && (mboSet.count() > 0)) {
				  // Exists table customization.
				  def_flds_bool = false;
				  Log4jLogger.info(ExcelConfig.class," There is a customization in " + tableMboName);
					MboRemote mboR = mboSet.moveFirst();
					while (mboR != null) {
					  attrName = mboR.getString("ATTRIBUTENAME");
					  attrName = attrName.toLowerCase();
					  Log4jLogger.debug(ExcelConfig.class," Attribute = " + attrName);
						if(!dataAttributes.contains(attrName)) {
							dataAttributes.add(attrName);
							Log4jLogger.debug(ExcelConfig.class, " " + attrName + " will be shown.");
						}
						mboR = mboSet.moveNext();
					}
				}
				else {
				  Log4jLogger.debug(ExcelConfig.class," No customization.");
				}
			}
		}
		
		Log4jLogger.debug(ExcelConfig.class," !can_dw_bool");
		if (!can_dw_bool) {
%>
				<html xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>
	
					<head>
						<!--[if gte mso 9]>
							<xml>
								<x:ExcelWorkbook>
									<x:ExcelWorksheets>
										<x:ExcelWorksheet>
											<x:WorksheetOptions>
												<x:Selected/>
											</x:WorksheetOptions>
										</x:ExcelWorksheet>
									</x:ExcelWorksheets>
								</x:ExcelWorkbook>
							</xml>
						<![endif]
						-->
					</head>
					<body><table><tr><td>
			<%=Utility.getMaxMessage(sessionContext,"access","CannotDownloadTableExcel").getMessage()%>
					</td></tr></table></body>
				</html>
	    <%
	      } else {
	    	    			if (def_flds_bool) {
	    	    			  // If there is no customization the default download will be used.
	    	    			  // Here we'll get the columns shown in the screen, default code.
	    	    				Log4jLogger.debug(ExcelConfig.class," Default Excel download.");
	    	    				while (jIterator.hasNext()) {
	    	    					ControlHandler tablecol = (ControlHandler) jIterator.next();
	    	    					String propertyvalue = tablecol.getProperties().getString(sessionContext, "dataattribute", "");
	    	    		
	    	    					//Need to convert all the dataattribute names to lower case so as to compare them
	    	    					propertyvalue = propertyvalue.toLowerCase();
	    	    					if(!Utility.isNull(propertyvalue)) {
	    	    						if(!dataAttributes.contains(propertyvalue)) {
	    	    							dataAttributes.add(propertyvalue);
	    	    						}	
	    	    					}
	    	    				}
	    	    			}
	    	    			String[] arrDataAttributes = new String[dataAttributes.size()];
	    	    			for(int kIndex=0; kIndex<dataAttributes.size();kIndex++) {
	    	    				arrDataAttributes[kIndex] = (String) dataAttributes.get(kIndex);
	    	    			}
	    	    			String label = new String("");
	    %>
			<html xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>
	
				<head>
					<!--[if gte mso 9]>
						<xml>
							<x:ExcelWorkbook>
								<x:ExcelWorksheets>
									<x:ExcelWorksheet>
										<x:WorksheetOptions>
											<x:Selected/>
										</x:WorksheetOptions>
									</x:ExcelWorksheet>
								</x:ExcelWorksheets>
							</x:ExcelWorkbook>
						</xml>
					<![endif]
					-->
				</head>
	
				<body>
					<fieldset>
	<% 
						tableBean.getUserAndQbeWhere();
	%>
					</fieldset>
					<table>
						<tr>
	<%
						for (int z=0; z < arrDataAttributes.length; z++) {
							//Get the dataattribute "title" instead of the dataattribute "name"
							label = tableBean.getTitle(arrDataAttributes[z]);
							if (Utility.isNull(label)) {
								label = arrDataAttributes[z];
							}
	%>
							<td>
								<%=label%>
							</td>
	<%
						}
	%>
						</tr>
	<%		
						MboSetRemote tblRemote = tableBean.getMboSet();
						MboSetRemote dnldRemote = null;
						MboSetRemote newParent = null;
						if (!(tblRemote instanceof NonPersistentMboSetRemote)) {
							if (tblRemote instanceof FauxMboSetRemote 
							    && tableBean.getParent() != null 
							    && tblRemote.getRelationship() != null) {
								try {
									MboSetRemote parentRemote = tableBean.getParent().getMboSet();
									long unigueid = parentRemote.getMbo().getUniqueIDValue();
									newParent = tableBean.getMXSession().getMboSet(parentRemote.getName());
									MboRemote parentMbo = newParent.getMboForUniqueId(unigueid);
									dnldRemote = parentMbo.getMboSet(tblRemote.getRelationName());
								}
								catch (Throwable thr) {
									//Problem use table's bean.
								}
							}
							else {
								 dnldRemote = tableBean.getMXSession().getMboSet(tblRemote.getName());
							}
						}
						int count = 0;
						if (dnldRemote != null) {
							dnldRemote.setFlag(MboConstants.DISCARDABLE, true);
							dnldRemote.setWhere(tblRemote.getCompleteWhere());
							dnldRemote.setOrderBy(tblRemote.getOrderBy());
							dnldRemote.reset();
							count = dnldRemote.count();
						}
						else {
							dnldRemote = tblRemote;
							count = tblRemote.count();
							int maxRows = Integer.parseInt(RequestHandler.getWebClientProperty("webclient.maxselectrows", "200"));
							if (count > maxRows) {
								count = maxRows;
							}
						}
						for(int j=0; j< count; j++) {
							MboValueData[] row = dnldRemote.getMbo(j).getMboValueData(arrDataAttributes);
	%>
							<tr>
	<%
							for(int k=0; k<row.length;k++) {
								String strData = (String) row[k].getData();
								if (strData == null)
									strData = "";
	%>
								<td><%=strData%></td>
	<%
							}
	%>
							</tr>
	<%
						}	
						if (tblRemote != dnldRemote) {
							dnldRemote.reset();
							dnldRemote.close();
							if (newParent != null) {
								newParent.reset();
								newParent.close();						
							}
						}
	%>					
					</table>
				</body>
			</html>
	<%
		}	
	}
%>